package com.xyf.sys.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.xyf.sys.domain.UserAddress;
import com.xyf.sys.service.IBaiduCloudService;
import com.xyf.sys.util.WechatHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;

/**
 * @Author R-H
 * @Date 2024/3/101256
 * @Description
 */
@Service
@Slf4j
public class BaiduCloudServiceImpl implements IBaiduCloudService {

    @Value("${baidu.apiKey}")
    private String apiKey;

    @Value("${baidu.secretKey}")
    private String secretKey;

    @Override
    public String getAccessToken(String apiKey, String secretKey) {
        String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + apiKey + "&client_secret=" + secretKey + "&";
        String res = HttpUtil.post(url, new JSONObject());
        JSONObject jsonObject = JSONObject.parseObject(res);
        return jsonObject.getString("access_token");
    }

    @Override
    public UserAddress textToAddress(String text) throws UnsupportedEncodingException {
        String url = "https://aip.baidubce.com/rpc/2.0/nlp/v1/address?access_token=" + this.getAccessToken(apiKey, secretKey);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("text", text);
        byte[] bytes = WechatHttpUtil.doWechatPost(url, jsonObject);
        JSONObject object = JSONObject.parseObject(new String(bytes, "utf-8"));
        log.info("text ocr {}", object.toString());
        UserAddress address = new UserAddress();
        address.setProvince(object.getString("province"));
        address.setCity(object.getString("city"));
        address.setCode(object.getString("province_code"));
        address.setArea(object.getString("county"));
        address.setArea(object.getString("county"));
        address.setTown(object.getString("town") == null? "" : object.getString("town"));
        address.setAddress(object.getString("detail"));
        address.setName(object.getString("person"));
        address.setMobile(object.getString("phonenum"));
        address.setText(text);
        return address;
    }
}
